$(function () {


    //检查时是否是分享出去的页面，添加悬浮按钮
    checkSharedPage();
    //默认加载目录
    var catalogTag = $("#buttons-tab>a")[1];
    var tagId = catalogTag.id;
    climg();
    changeTabs(tagId);
    //初始化播放
    if(initPlayCatalogId > 0){
        playCatalogId = initPlayCatalogId;
        goPlay(courseId,playCourseId,playCatalogId,playCallback);
    }
    Zepto("body").on('click','#buttons-tab>a',function () {
        var _this = Zepto(this);
        if(_this.hasClass('active')) return;
        var _id = this.id;
        changeTabs(_id);
    }).on('click','.select-course-box',function () {
        //操作类型，1上，2下
        var _type = Zepto(this).data('type');
        var index = parseInt(Zepto("#pc-index-box").val());
        if(_type==1){//上一个
            index --;
        }
        if(_type==2){//下一个
            index ++;
        }
        if(index < 0){
            Zepto.toast('前面没有课程了');
            return;
        }
        var list = Zepto("#course-package-list>li");
        if(index >= list.length){
            Zepto.toast('后面没有课程了');
            return;
        }
        var _courseId = getIndexCourseId(index);
        getCourseCatalog(_courseId);
        Zepto("#pc-index-box").val(index);
    }).on('click','#c-sign-up-btn',function () {//立即报名
        var courseId = $("#courseId").val();
        var shareKey = getParameter("shareKey");
        if(shareKey!=null && $.trim(shareKey) != ''){
            window.location.href=baseloaction + "/mobile/uc/order/initPayOrder?orderType=COMMON&shopData="+courseId+"-COURSE-1-"+shareKey;
        }else{
            window.location.href=baseloaction + "/mobile/uc/order/initPayOrder?orderType=COMMON&shopData="+courseId+"-COURSE-1";
        }
    }).on('click','.free-bm-box',function(){//免费报名
        var _this = Zepto(this);
        var payType = _this.data('paytype');
        var classesUrl= $('#classesUrl').val();
        isLogin(function () {
            genFreeOrder(payType,courseId+'-COURSE-1',function(){
                _this.remove();
                Zepto('#c-audition-btn').remove();
                Zepto.toast('免费报名成功');
            });
            if (classesUrl != ""){
                $.confirm('免费报名成功,快去加入班级吧!', function () {
                    window.location.href = classesUrl;
                });
            }
        });
    }).on('click', '#c-comment-btn', function () {
        var courseId = $('#courseId').val();
        var playId = $("#playId").val();
        isLogin(function () {//验证登录
            if(playCourseId == 0){
                $.toast('只允许反馈正在学习的章节呦');
                return;
            }
            //评价前做验证
            checkComment(courseId,playId,courseFeedback);
        })
    }).on('click','aside.course-play-btn,#c-audition-btn',function () {//页面底部的免费试听按钮、课程图片中播放按钮点击
        //得到目录ID
        var catalogId = $('#playCatalogId').val();
        //如果播放节点为0获取播放目录的第一个节点
        if(catalogId==0){
            var play_list  =  $("#course-catalog-list li a[data-catalog]");
            if(play_list==null && play_list.length<=0){
                $.toast('没有可播放的节点');
            }else{
                var auditionList = $('span.free-tag');
                if(auditionList != null && auditionList != 'undefined' && auditionList.length>0){
                    var em = auditionList[0];
                    catalogId = $(em).data('id');
                }else {
                    catalogId=  $(play_list[0]).data('catalog');
                }
            }
        }
        playCourseId = $('#playCourseId').val();
        //执行播放
        isLogin(function () {
            goPlay(courseId,playCourseId,catalogId,playCallback);
        });
    }).on('click','.c-play-smallIco>em.icon-edit',function () {//随堂练习
        if(!buy){
            guideBuyCourse("还为购买此课程，建议立即购买此课，学习更多章节！",courseId);
            return;
        }
        var catalogId = Zepto(this).data('id');
        var questionIds = Zepto(this).data("question");
        isLogin(function () {
            var $video = document.getElementsByTagName('video')[0];
            var type =1;
            if($video!=null&&$video!=undefined) {
                type=2;
            }
            popupExerciseConfirm(courseId,catalogId,questionIds,type);
        })
    }).on('click','em.icon-sanjiao,span[data-id]',function(){//点击目录播放
        var catalogId = Zepto(this).data('id');
        playCourseId = $('#playCourseId').val();
        isLogin(function () {
            goPlay(courseId,playCourseId,catalogId,playCallback);
        })
    }).on('click',".online-consultation",function () {
        var content = $(this).data('course');
        window.open(content,'newwindow', 'toolbar=no,scro.llbars=yes,location=no,resizable=no,top=200,left=300,width=800,height=600');
    }).on('click',"em.icon-hudongpiaoicon05",function () {
        var catalogid= $(this).data('catalogid');
        var courseId = $("#courseId").val();
       var that= $(this);
        downloadDatum(courseId,catalogid,that);
    }).on("click","#qa-teacher-btn",function(){
            var playCourseId=null;
            if(courseTypeKey =="PACKAGE"){
                playCourseId=$("#playCourseId").val();
            }else{
                playCourseId =0;
            }
            window.location.href=baseloaction +'/mobile/teacher/teacherInfo?isCourse=true&teacherId='+$(this).data("id")+"&catalogId="+$("#playId").val()+"&courseId="+courseId+"&packageCourseId="+playCourseId;
    })
        .on("click","#qa-teacher-btn2",function(){
            if($(this).data("type") == 0){
                $.toast('只能向正在播放的章节问答专家提问');
                return;
            }
            if($(this).data("type") == 2){
                $.toast('当前学习的章节，讲师不是问答专家无法进行提问');
                return;
            }
            var playCourseId=null;
            if(courseTypeKey =="PACKAGE"){
                playCourseId=$("#playCourseId").val();
            }else{
                playCourseId =0;
            }
            window.location.href=baseloaction +'/mobile/teacher/teacherInfo?isCourse=true&teacherId='+$(this).data("id")+"&catalogId="+$("#playId").val()+"&courseId="+courseId+"&packageCourseId="+playCourseId;
        }).on("click","#interact",function(){
        getClass();
    }).on("click",".course-class-item",function(){
        window.location.href=baseloaction+"/mobile/class/info?classId="+$(this).data("id");
    }).on("click",".cInfoShare-btn",function(){
        posters( Zepto('#courseName').text(),window.location.href+"&shareKey="+SHARE_KEY,Zepto('#lookNum').val(),1)
    });

    validationStatus();

    //暴露给外部的回调方法
    playCallbackExposed =playCallback;
    /**
     * 播放回调
     * @param material 素材对象
     */
    function playCallback(material){
        var playId = $("#playId").val();
        $(".master_node,.item-content").removeClass('active');
        $("#course-catalog-box-"+playId).addClass("active");

        var teacherId = material.teacherId;
        setTimeout(function () {
            $("#qa-teacher-btn").hide();
            if(buy){
                $.ajax({
                    url:baseloaction +'/mobile/course/findQaTeacherById',
                    type:'post',
                    dataType:'json',
                    data:{
                        'teacherId':teacherId
                    },
                    success:function (result) {
                        if(result.success==true){
                            var teacher = result.entity;
                            var test2 = document.getElementById('qa-teacher-btn2');

                            if(teacher!=null&&teacher.isQuestion=="1"){
                                $("#qa-teacher-btn").attr({
                                    'style':'display:table-cell !important'
                                });
                                var test = document.getElementById('qa-teacher-btn');
                                test.dataset.id =teacherId;
                                test2.dataset.id =teacherId;
                                test2.dataset.type =1;
                            }else{
                                test2.dataset.type =2;
                            }
                        }
                    }
                });
            }
        },1000);
    }

    checkBuy();
    /**
     * 获取下一个/上一个套餐课程的ID
     * @param index 下标
     * @return {*} 课程ID
     */
    function getIndexCourseId(index) {
        var list = Zepto("#course-package-list>li");
        if(index >= 0 && index < list.length){
            var courseId = Zepto(list[index]).data('id');
            var courseName = Zepto(list[index]).data('name');
            Zepto("#current-course-name").text(courseName);
            return courseId;
        }
        return 0;
    }

    /**
     * 通过课程ID获取下标
     * @param courseId 课程
     */
    function getCourseIndex(courseId) {
        var list = Zepto("#course-package-list>li");
        var index = 0;
        $.each(list,function (i,em) {
            var id = $(em).data('id');
            if(id == courseId){
                index = i;
            }
        });
        return index;
    }

    /**
     * 获取课程目录
     * @param courseId 课程目录ID
     */
    function getCourseCatalog(_courseId) {
        Zepto.ajax({
            url:baseloaction +'/mobile/course/findCourseCatalog',
            type:'post',
            dataType:'html',
            data:{
                'buyCourseId':courseId,
                'courseId':_courseId
            },
            success:function (result) {
                Zepto("#course-catalog-list").html(result);
            },
            error:function (error) {
                Zepto.toast('系统错误，加载目录失败');
            }
        });
    }

    // 详情 目录 反馈切换
    function changeTabs(obj) {
        if(buy){
            Zepto('nav.course-info-bar-tab').addClass('mfHide');
        }
        switch (obj) {
            case 'table':
                Zepto('nav.course-info-bar-tab').addClass('mfHide');
                if(courseTypeKey=='PACKAGE'){//如果是套餐

                    if(courseId == 0){
                        var html = "";
                        html += "<section class=\"no-data__wrap\">\n"
                        html += "   <em>&nbsp;</em>\n"
                        html += "   <p>亲，小编正在整理中~~</p>\n"
                        html += "</section>"
                        Zepto("#course-catalog-list").html(html);
                        return;
                    }
                    var _courseId  = 0;
                    if(packageCourseId > 0){
                        var _index = getCourseIndex(packageCourseId);
                        _courseId  = getIndexCourseId(_index);
                    }else{
                        _courseId  = getIndexCourseId(0);
                    }
                    getCourseCatalog(_courseId);
                    Zepto("#pc-index-box").val(0);
                    playCourseId = _courseId;
                }else{//如果是非套餐
                    playCourseId  = courseId;
                    getCourseCatalog(courseId);
                }
                break;
            case 'comments':
                Zepto('nav.course-info-bar-tab').addClass('mfHide');
                ajaxCommentList(1);
                break;
            case'interact':
                Zepto('nav.course-info-bar-tab').addClass('mfHide');
                break;
            default:
                if(!buy){
                    Zepto('nav.course-info-bar-tab').removeClass('mfHide');
                }
                break;
        }
    }
    var buy = false;
    // 检查课程购买
    function checkBuy() {
        Zepto.ajax({
            url: baseloaction + '/mobile/course/ajax/check/buy',
            data: {'courseId': courseId},
            dataType: 'json',
            success: function (response) {
                if (response.success) {
                    buy = true;
                    Zepto('nav.course-info-bar-tab').addClass('mfHide');
                    Zepto(".member-box").css('display','none');
                }else{
                    Zepto('nav.course-info-bar-tab').removeClass('mfHide');
                    Zepto(".member-box").css('display','block');
                }
            },
            error: function () {
                console.log('error');
            }
        });
    }

    var desc = $('#course-summary').val();
    //课程分享
    wShareFn.Focus.init({
        ele: '#c-share-btn',
        opt: checkBaseShare(shareChannel),
        title : Zepto('#courseName').text(),
        lookNum : Zepto('#lookNum').val(),
        url : window.location.href,
        desc : desc,
        img:$(".course-play-bg").css("backgroundImage").replace('url(','').replace(')','').replace(/"/g,"")
    });
    Zepto('body').on('click', '#course-submit-feedback', function () {//提交反馈
        var quality = Zepto('#quality').val();
        var teach = Zepto('#teach').val();
        var feel = Zepto('#feel').val();
        var comment = Zepto('#comment').val();
        var courseId = Zepto('#courseId').val();
        var catalogId = Zepto('#playId').val();
        saveComment(quality,teach,feel,comment,courseId,catalogId,function () {
            Zepto('#course-comment-close').trigger('click');
            Zepto('#c-comment-btn').data("eval","已经评论过了")
        });
    });

    function climg (){
      var that =   $("#details img");
        that.forEach(function(item, index){
           var _that = Zepto(item);
            var width =_that.css('width');
            if(parseInt(width)>=320){
                _that.css({
                    'width': '100%',
                    'height' : 'auto'
                });
            }
      });
    }

    /**
     *
     * @param catalogId 播放的节点id
     * @param type 弹出框位置
     */
    autoOpenExerciseConfirm =  function autoOpenExerciseConfirm(catalogId,type){
        if(!buy){
            guideBuyCourse("还为购买此课程，建议立即购买此课，学习更多章节！",courseId);
            return;
        }
        var playCatalog  = $("a[data-catalog="+"'"+catalogId+"'"+"]");
        if(playCatalog.length>0){
            var playEdit=playCatalog.parent('li').find('.c-play-smallIco>em.icon-edit');
            if(playEdit.length>0){
                popupExerciseConfirm(courseId,playEdit.data('id'),playEdit.data("question"),type);
            }
        }
    }

    //领取优惠券操作表
    $(document).on('click', '.selectOpcardBtn', function () {
        loadCourseCode(courseId);
    });

    //加载最后更新的
    setTimeout(function () {
        if(contextStatus==1){
            getNewCatalog(courseId,courseTypeKey);
        }
    },200);

    /**
     * 获取最新的目录
     * @param courseIds 课程ID串
     * @param courseType 课程类型
     */
    function getNewCatalog(courseIds,courseType) {
        $.ajax({
            url: baseloaction +'/mobile/course/getNewCatalog',
            type:'post',
            dataType:'json',
            data:{
                'courseIds':courseIds
            },
            success:function (result) {
                if(result.success==true){
                    var obj = result.entity;
                    if(obj !=null){
                        var context = '';
                        if(courseType =='PACKAGE') {//如果是套餐
                            context += obj.course.courseName+'-';
                        }
                        var parentCatalog = obj.parentCatalog;
                        if(parentCatalog != null){
                            context+= parentCatalog.catalogName + "-";
                        }
                        context+= obj.catalogName;
                        $("#last-update").text(context);
                    }
                }
            }
        });
    }

    function  getClass(){

        $.ajax({
            url:baseloaction +'/mobile/class/getCourseRelevanceClasses',
            type:'post',
            dataType:'json',
            data:{
                'courseId':courseId
            },
            success:function (result) {
                if(result.success==true){
                   var entity = result.entity;

                   if(entity.length>0){

                       var html='';
                       entity.forEach(function (item, index) {
                         html+=  '<li data-id='+item.id+' class="wm-whiteBox course-class-item">\n' +
                           '                                            <a  class="text-center">\n' +
                           '                                                <section class="course-class-pic-bx">\n' +
                           '                                                    <img class="wm-img" width="80" height="80"  src="'+item.imageMap.mobileUrlMap.small+'">\n' +
                           '                                                </section>\n' +
                           '                                                <section class="ellipsis-rows">\n' +
                           '                                                    <span class="fs7 c-333">'+item.name+'</span>\n' +
                           '                                                </section>\n' +
                           '                                                <section class="mt5">\n' +
                           '                                                    <span class="fs4 c-888">'+item.topicCount+'个话题</span>\n' +
                           '                                                </section>\n' +
                           '                                            </a>\n' +
                           '                                        </li>'
                       });

                       $(".course-class-item-box").html(html);
                       //获取一个控件的宽度
                       setTimeout(function(){

                           $(".re-class").forEach(function (item, index) {
                               $(item).attr("style","display:black")
                           });
                           $(".course-class-item-box").width( ($('.course-class-item').length+1) *  $('.course-class-item').eq(0).width())
                       },100);

                   };

                }
            }
        });
    }

    function setShareKeyToCookie() {
        // 将shareKey 放入sessionStorage
        document.cookie = "shareKey=" + escape(shareKey) + ";shareKey=" + shareKey;
        
    }

    /**
     * 加载课程的活动
     */
    setTimeout(function () {
        var price = $("#price").val();
        courseInfoActivity(price);
    },300);
    isBuy =buy;
});
var playCallbackExposed;

var autoOpenExerciseConfirm;
//是否购买
var isBuy;